import {getContentApi, getProjectApi} from '@/services'
import router from 'umi/router'
export default {
  namespace: 'content',

  state: {
    content: {
      load: false,
      data: null,
    },

    project: {
      load: false,
      data: {
        menus: [],
        top_menus: [],
        top_menus_map: {},
      },
    },

    language: {
      load: false,
      data: {},
    },
  },

  effects: {
    * redirect({payload}) {
      if (payload) {
        router.push(payload)
      }
    },
    * getContentAction(_, {put, select}) {
      const oldContent = yield select(state => state.content.content)
      if (oldContent && oldContent.load) {
        return
      }

      yield put({
        type: 'mergeContent',
        payload: {load: true},
      })

      // 查询数据
      const content = yield getContentApi()
      yield put({
        type: 'mergeContent',
        payload: {data: content},
      })
    },

    * getProjectAction(_, {put, select}) {
      const oldProject = yield select(state => state.content.project)
      if (oldProject && oldProject.load) {
        return
      }

      yield put({
        type: 'mergeProject',
        payload: {load: true},
      })

      // 查询数据
      const content = yield getProjectApi()
      content.top_menus_map = {}
      content.top_menus.forEach(v => {
        content.top_menus_map[v.url] = v
      })

      yield put({
        type: 'mergeProject',
        payload: {data: content},
      })
    },
  },
  reducers: {
    mergeContent(state, {payload}) {
      return {
        ...state,
        content: {
          ...state.content,
          ...payload,
        },
      }
    },
    mergeProject(state, {payload}) {
      return {
        ...state,
        project: {
          ...state.project,
          ...payload,
        },
      }
    },
  },
}
